<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" label-width="68px" size="mini">
      <el-row :gutter="20">
        <el-col :span="4">
          <el-form-item label="项目区域" prop="projectRegion">
            <el-select v-model="queryParams.projectRegion" clearable placeholder="请选择" @keyup.enter.native="handleQuery">
              <el-option v-for="dict in dict.type.cld_project_region" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="项目名称" prop="projectName">
            <el-input v-model="queryParams.projectName" clearable placeholder="请输入" @keyup.enter.native="handleQuery"/>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="员工姓名" prop="staffName">
            <el-input v-model="queryParams.staffName" clearable placeholder="请输入" @keyup.enter.native="handleQuery"/>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="确认状态" prop="isConfirm">
            <el-select v-model="queryParams.isConfirm" clearable placeholder="请选择" @keyup.enter.native="handleQuery">
              <el-option label="已确认" value="1"></el-option>
              <el-option label="待确认" value="0"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label-width="10px">
            <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-hasPermi="['cld:materialApply:add']" icon="el-icon-plus" plain size="mini" type="primary"
                   @click="handleAdd">添加领用信息
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="materialApplyList" border>
      <el-table-column align="center" label="项目区域" prop="projectRegion">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.cld_project_region" :value="scope.row.projectRegion"/>
        </template>
      </el-table-column>
      <el-table-column align="center" label="项目名称" prop="projectName"/>
      <el-table-column align="center" label="岗位编号" prop="projectPostNo"/>
      <el-table-column align="center" label="岗位" prop="projectPostName">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.cld_project_post" :value="scope.row.projectPostName"/>
        </template>
      </el-table-column>
      <el-table-column align="center" label="组别" prop="groupName">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.cld_project_groups" :value="scope.row.groupName"/>
        </template>
      </el-table-column>
      <el-table-column align="center" label="姓名" prop="staffName"/>
      <el-table-column align="center" label="性别" prop="staffSex"/>
      <el-table-column align="center" label="联系方式" prop="staffPhone"/>
      <el-table-column align="center" label="领用数量" prop="wareAllocateNumber"/>
      <el-table-column align="center" label="确认状态" prop="isConfirm">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.isConfirm == 0" type="success">待确认</el-tag>
          <el-tag v-if="scope.row.isConfirm == 1" type="danger">已确认</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="申请时间" prop="materialAllocateDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.materialAllocateDate) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="确认时间" prop="confirmTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.confirmTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
        <template slot-scope="scope">
          <el-button v-if="scope.row.approveStatus == 2" v-hasPermi="['cld:materialApply:edit']" size="mini" type="text" @click="handleViewOrAudit(scope.row, 1)">修改</el-button>
          <el-button v-hasPermi="['cld:materialApply:query']" size="mini" type="text" @click="handleViewOrAudit(scope.row, 3)">领用明细</el-button>
          <el-button v-if="scope.row.isConfirm == 0" v-hasPermi="['cld:materialApply:remove']" size="mini" type="text" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :limit.sync="queryParams.pageSize" :page.sync="queryParams.pageNum" :total="total"
                @pagination="getList"/>

    <!-- 添加或修改领用记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body width="80%">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" size="mini">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="项目仓库" prop="materialOutId">
              <treeselect v-model="form.materialOutId" :normalizer="normalizer" :options="wareProjectOptions"
                          placeholder="请选择" @select="handleTreeProjectSelectNode"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="个人仓库" prop="materialInId">
              <treeselect v-model="form.materialInId" :normalizer="normalizer" :options="wareJobOptions"
                          placeholder="请选择" @select="handleTreePostSelectNode"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button :disabled="!form.materialOutId" icon="el-icon-plus" plain size="mini" type="primary"
                       @click="handleAddCommodity">添加商品
            </el-button>
          </el-col>
        </el-row>
        <el-row>
          <el-table :data="form.detailsList" border>
            <el-table-column align="center" type="selection" width="55"/>
            <el-table-column align="center" label="商品类别" prop="commodityType"/>
            <el-table-column align="center" label="商品编号" prop="commodityNo"/>
            <el-table-column align="center" label="商品名称" prop="commodityName1"/>
            <el-table-column align="center" label="商品图片" prop="commodityImg" width="100">
              <template slot-scope="scope">
                <image-preview :height="50" :src="scope.row.commodityImg" :width="50"/>
              </template>
            </el-table-column>
            <el-table-column align="center" label="规格" prop="commoditySpec" width="80"/>
            <el-table-column align="center" label="单位" prop="unitName1" width="150"/>
            <el-table-column align="center" label="数量" prop="materialAllocateNumber" width="120">
              <template slot-scope="scope">
                <el-input v-model="scope.row.materialAllocateNumber"></el-input>
              </template>
            </el-table-column>
            <el-table-column align="center" label="当前库存" prop="wareCommodityNumber"/>
          </el-table>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 领用明细 -->
    <el-dialog :title="viewTitle" :visible.sync="viewOpen" append-to-body width="60%">
      <!--商品数据-->
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-descriptions :column="3" border>
          <el-descriptions-item label="项目仓库">{{ form.materialOutName }}</el-descriptions-item>
          <el-descriptions-item label="个人仓库">{{ form.materialInName }}</el-descriptions-item>
        </el-descriptions>
        <el-row style="padding-top: 20px;">
          <el-table :data="form.detailsList" border>
            <el-table-column align="center" label="商品类别" prop="commodityType"/>
            <el-table-column align="center" label="商品编号" prop="commodityNo"/>
            <el-table-column align="center" label="商品名称" prop="commodityName1"/>
            <el-table-column align="center" label="规格" prop="commoditySpec" width="80"/>
            <el-table-column align="center" label="单位" prop="unitName1" width="150"/>
            <el-table-column align="center" label="数量" prop="materialAllocateNumber" width="120"/>
            <el-table-column align="center" label="单价" prop="costPrice" width="120">
              <template slot-scope="scope">
                {{ toMoney(scope.row.costPrice) }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="总价" prop="totalMoeny" width="120">
              <template slot-scope="scope">
                {{ toMoney(scope.row.totalMoeny) }}
              </template>
            </el-table-column>
          </el-table>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="type == 2" type="primary" @click="handleAuditOptions(1)">通过</el-button>
        <el-button v-if="type == 2" type="primary" @click="handleAuditOptions(2)">驳回</el-button>
        <el-button @click="viewOpen = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 选择商品 -->
    <el-dialog :close-on-click-modal="false" :destroy-on-close="true" :visible.sync="isCommodityOpen" append-to-body title="选择商品"
               width="80%">
      <ErpCommodity v-if="isCommodityOpen" :notCommodityIds="notCommodityIds" :wareId="form.materialOutId"
                    @SelectionChange="handleSelectionChange">
      </ErpCommodity>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitSelectedCommdity">确 定</el-button>
        <el-button @click="isCommodityOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addMaterialAllocate,
  auditCldMaterialAllocate,
  delMaterialAllocate,
  getMaterialAllocate,
  listMaterialApply,
  updateMaterialAllocate
} from "@/api/cld/materialAllocate";
import {listErpWareHouse} from "@/api/erp/ErpWareHouse";
import ErpCommodity from '@/views/erp/ErpCommodity/selectedCommodity'
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "MaterialApply",
  dicts: ["cld_project_region", "cld_project_post", "cld_project_groups"],
  components: {
    Treeselect,
    ErpCommodity
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 领用记录表格数据
      materialApplyList: [],
      // 弹出层标题
      title: "",
      // 领用记录
      viewTitle: "",
      // 是否显示弹出层
      open: false,
      // 领用明细
      viewOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        allocateType: 1,
        projectRegion: null,
        projectName: null,
        staffName: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      // 项目仓库
      wareProjectOptions: [],
      // 岗位仓库
      wareJobOptions: [],
      // 操作类型
      type: 1,
      // 选择商品页面
      isCommodityOpen: false,
      temporyList: []
    };
  },
  created() {
    this.getList();
    this.getTreeselect(1);
  },
  methods: {
    /** 查询领用记录列表 */
    getList() {
      this.loading = true;
      listMaterialApply(this.queryParams).then((response) => {
        this.materialApplyList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        materialAllocateId: null,
        materialOutId: null,
        materialOutPerson: null,
        materialInId: null,
        materialInPerson: null,
        remark: "个人仓领用",
        allocateType: 1,
        confirmTime: null,
        isConfirm: null,
        detailsList: [],
      };
      this.resetForm("form");
    },
    // 选择商品
    handleAddCommodity() {
      // 设置商品过滤id
      this.notCommodityIds = this.form.detailsList?.map(item => item.commodityId);
      this.isCommodityOpen = true;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 转换仓库管理数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.wareId,
        label: node.wareName,
        children: node.children,
      };
    },
    /** 查询仓库管理下拉树结构 */
    getTreeselect(wareType) {
      listErpWareHouse({
        wareType: wareType,
        warePid: this.form.lssuedWareId,
        params: {
          notIdentifier: 3,
        },
      }).then((response) => {
        if (wareType == 1) {
          this.wareProjectOptions = this.handleTree(
            response.data,
            "wareId",
            "warePid"
          );
        } else {
          this.wareJobOptions = this.handleTree(
            response.data,
            "wareId",
            "warePid"
          );
        }
      });
    },
    // 仓库选择
    handleTreeProjectSelectNode(e) {
      // 查询个人仓
      this.form.lssuedWareId = e.wareId;
      this.form.projectId = e.projectId;
      this.getTreeselect(2);
    },
    handleTreePostSelectNode(e) {
      this.form.postId = e.staffId;
    },
    // 商品选择
    handleSelectionChange(selection) {
      this.temporyList = selection;
    },
    // 确定选择商品
    submitSelectedCommdity() {
      this.form.detailsList = this.temporyList;
      this.isCommodityOpen = false;
    },
    /** 删除商品 */
    handleDeleteCommodity(row) {
      const index = this.form.detailsList.indexOf(row);
      if (index > -1) {
        this.form.detailsList.splice(index, 1);
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.type = 1;
      this.title = "领用记录";
    },
    /** 修改按钮操作 */
    handleViewOrAudit(row, type) {
      this.reset();
      this.type = type;
      getMaterialAllocate(row.materialAllocateId).then(res => {
        this.form = res.data;
        if (type == 1) {
          this.title = '修改';
          this.open = true;
        } else {
          this.viewTitle =
            this.form.staffName +
            "-" +
            this.parseTime(this.form.materialAllocateDate, "{y}-{m}-{d}") +
            "领取详情";
          this.viewOpen = true;
          // 查询个人仓
          this.getTreeselect(2);
        }
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.materialAllocateId != null) {
            updateMaterialAllocate(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMaterialAllocate(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleAuditOptions(type) {
      this.form.approveStatus = type;
      if (type == 2) {
        this.$prompt('', '驳回原因', {
          center: true,
          inputType: 'textarea',
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        }).then(({value}) => {
          this.form.rejectReason = value;
          this.handleAudit();
        })
      } else {
        this.handleAudit();
      }
    },
    // 审核
    handleAudit() {
      auditCldMaterialAllocate({
        materialAllocateId: this.form.materialAllocateId,
        approveStatus: this.form.approveStatus,
        rejectReason: this.form.rejectReason
      }).then(res => {
        this.$modal.msgSuccess("操作成功");
        this.viewOpen = false;
        this.getList();
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const materialApplyIds = row.materialAllocateId || this.ids;
      this.$modal
        .confirm(
          '是否确认删除该条领用记录由项目仓（' + row.projectName + '）下发至员工仓（' + row.staffName + '）的数据项？'
        )
        .then(function () {
          return delMaterialAllocate(materialApplyIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {
        });
    },
  },
};
</script>
